<template>
  <div class="page-questionnaire-list">
    <el-card>
      <el-row
        align="end"
        class="page-coach-list-search"
        justify="space-between"
        type="flex"
      >
        <el-col :span="24">
          <el-form ref="form" :inline="true" :model="form">
            <el-form-item label="问卷类型: ">
              <!--              clearable-->
              <el-select
                v-model="form.surveyType"
                placeholder="全部"
                @change="loadData"
              >
                <el-option
                  v-for="item in surveyTypes"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="primary"
                @click="submitForm(form)"
              >查找
              </el-button>
              <!--              <el-button-->
              <!--                @click="resetForm(form)"-->
              <!--              >清空-->
              <!--              </el-button>-->
              <el-button
                :loading="allDownloading"
                icon="el-icon-download"
                @click="clickOnExport"
              >导出全部
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :cell-style="{ textAlign: 'center' }"
        :data="tableData"
        :header-cell-style="{ textAlign: 'center' }"
        height="70vh"
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <!--        <el-table-column label="问卷题目" prop="surveyTitle" />-->
        <el-table-column label="问卷类型" prop="surveryTypeDesc" width="100" />
        <el-table-column v-if="!isH5List" label="用户名" prop="nickName" />
        <el-table-column v-if="isH5List" label="用户名" prop="userName" />
        <el-table-column label="用户手机号码" prop="phone" />

        <!--        <el-table-column label="答题时间" prop="createTime" width="160" />-->
        <el-table-column fixed="right" label="操作" width="210">
          <template #default="scope">
            <el-button
              icon="el-icon-search"
              plain
              size="small"
              type="primary"
              @click.prevent="handleDetail(scope.row)"
            >查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row class="page-questionnaire-list-pagination">
        <el-col>
          <el-button
            v-if="currentChoose && currentChoose.length > 0"
            :loading="downloading"
            icon="el-icon-download"
            @click="clickOnExportSelection()"
          >导出选中数据
          </el-button>
        </el-col>
        <el-col>
          <pagination
            v-show="total > 0"
            :background="false"
            :limit.sync="pageSize"
            :page.sync="currentPage"
            :total="total"
            @pagination="loadData"
          />
        </el-col>
      </el-row>
    </el-card>

    <questionnaire-detail-dialog
      v-if="detailShown"
      ref="detailDialog"
      @close="detailDialogClosed"
    />
  </div>
</template>

<script>
import {
  ExportQuestionnaires,
  GetH5List,
  PostSurveyDetailList
} from '@/api/api'
import Pagination from '@/components/Pagination'
import QuestionnaireDetailDialog from '@/views/questionnaire/components/questionnaireDetailDialog.vue'

const SurveyType = [
  {
    label: '问卷一',
    value: '1,2,3,4'
  },
  {
    label: '问卷二',
    value: '5'
  },
  {
    label: 'H5问卷',
    value: 'H5'
  }
]
export default {
  components: {
    QuestionnaireDetailDialog,
    Pagination
  },
  data() {
    return {
      downloading: false,
      allDownloading: false,
      detailShown: false,
      surveyTypes: SurveyType,
      answers: [],
      form: {
        surveyType: '1,2,3,4'
      },
      tableData: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      currentChoose: []
    }
  },
  computed: {
    isH5List() {
      return this.form.surveyType === 'H5'
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      if (this.form.surveyType === 'H5') {
        await this.loadH5Data()
        return
      }
      try {
        if (this.loading) {
          return
        }
        this.loading = true

        const { data } = await PostSurveyDetailList(this.handleRequestParams())

        const { rows, total, code, msg } = data
        this.loading = false

        if (code !== 200) {
          this.$message.error([code, msg])
          return
        }
        this.total = total
        this.tableData = rows.map((item) => {
          // item.weekList = this.handleCoachConfigList(item.configList)
          item.surveryTypeDesc = item.surveyTypes.includes(5)
            ? '问卷二'
            : '问卷一'
          return item
        })
      } catch (e) {
        this.loading = false
        console.error(e)
      }
    },
    async loadH5Data() {
      try {
        if (this.loading) {
          return
        }
        this.loading = true

        const { data } = await GetH5List(this.handleRequestParams()) // GetSurveyDetailList(this.handleRequestParams())

        console.log('h5 list ', data)
        const { rows, total, code, msg } = data
        this.loading = false

        if (code !== 200) {
          this.$message.error([code, msg])
          return
        }
        this.total = total
        this.tableData = rows.map((item) => {
          item.surveryTypeDesc = 'H5'
          return item
        })
      } catch (e) {
        this.loading = false
        console.error(e)
      }
    },

    handleRequestParams() {
      if (this.form.surveyType === 'H5') {
        let queryStr = ''
        queryStr += `pageNum=${this.currentPage}&`
        queryStr += `pageSize=${this.pageSize}`
        return queryStr
      }

      let queryStr = ''
      if (this.form.surveyType && this.form.surveyType.length > 0) {
        queryStr += `surveyType=${this.form.surveyType}&`
        // const typeArr = this.form.surveyType.split(',')
        // if (typeArr && typeArr.length) {
        //   typeArr.forEach((item, index) => {
        //     queryStr += `surveyType=${item}`
        //     queryStr += '&'
        //   })
        // }
      }

      queryStr += `pageNum=${this.currentPage}&`
      queryStr += `pageSize=${this.pageSize}`
      return queryStr
    },
    submitForm(formEl) {
      // if (!formEl)
      // this.getCoachData(formEl)
    },
    resetForm(formEl) {
      if (!formEl) return
      this.form = {
        type: ''
      }
    },
    clickOnExport() {
      this.requestExportAll()
    },
    clickOnExportSelection() {
      this.requestExportPartial(
        this.currentChoose.map((item) => {
          return item.id
        })
      )
    },
    detailDialogClosed() {
      this.detailShown = false
    },
    handleSelectionChange(row) {
      this.currentChoose = row
      // this.currentChoose.push(row)
    },
    handleDetail(item) {
      this.detailShown = true
      this.$nextTick(() => {
        if (this.isH5List) {
          this.$refs.detailDialog.visable = true
          this.$refs.detailDialog.surveyTypes = ['H5']
          // this.$refs.detailDialog.userId = item.id
          this.$refs.detailDialog.h5Id = item.id
          this.$refs.detailDialog.reload()
          return
        }
        this.$refs.detailDialog.visable = true
        this.$refs.detailDialog.surveyTypes = item.surveyTypes
        this.$refs.detailDialog.userId = item.id
        this.$refs.detailDialog.h5Id = item.id
        this.$refs.detailDialog.reload()
      })
    },
    // async requestExportAll() {
    //   await ExportQuestionnaires({})
    // },
    // async requestExportPartial(ids) {
    //   await ExportQuestionnaires({ ids: ids })
    // },
    async requestExportAll() {
      if (this.allDownloading) {
        return
      }
      this.allDownloading = true
      await ExportQuestionnaires({}, '患者数据', (loaded) => {
        console.log('export all loaded', loaded)
      })
      this.allDownloading = false
    },
    async requestExportPartial(ids) {
      if (this.downloading) {
        return
      }
      this.downloading = true
      // console.log(ids, ids.join(','))
      await ExportQuestionnaires({ ids: ids })
      this.downloading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.page-questionnaire-list {
  padding: 20px;
  min-height: 80vh;
  background-color: #f9f9f9;

  &-search {
  }

  &-handle {
    margin: 0 0 30px 0;
  }

  &-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
